package com.devilwwj.http.core;

import android.os.AsyncTask;
import android.os.Build;

import com.devilwwj.http.callback.OnProgressUpdatedListener;
import com.devilwwj.http.exception.HttpException;

import org.apache.http.HttpResponse;

import java.net.HttpURLConnection;

/**
 * Created by devilwwj on 15/7/21.
 */
public class RequestAsyncTask extends AsyncTask<Void, Integer, Object> {


    private Request request;

    public RequestAsyncTask(Request request) {
        this.request = request;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }


    @Override
    protected Object doInBackground(Void... params) {
        if (request.iCallback != null) {
            Object o = request.iCallback.preRequest();
            if (o != null) {
                return o;
            }
        }
        // TODO 这里进行网络请求
        return request(0);
    }

    public Object request(int retry) {
        try {
            // FIXME: if you read the source code of Volley, you will also find this config
            // FIXME: you can also define a param in @Request to config outside
            if (Build.VERSION.SDK_INT >= 9) {

                HttpURLConnection connection = HttpURLConnectionUtil.execute(request, !request.enableProgressUpdated ? null : new OnProgressUpdatedListener() {
                    @Override
                    public void onProgressUpdate(int curPos, int contentLength) {
                        publishProgress(Request.STATE_UPLOAD, curPos, contentLength);
                    }
                });
                if (request.enableProgressUpdated) {
                    return request.iCallback.handle(connection, new OnProgressUpdatedListener() {
                        @Override
                        public void onProgressUpdate(int curPos, int contentLength) {
                            publishProgress(Request.STATE_DOWNLOAD, curPos, contentLength);
                        }
                    });
                } else {
                    return request.iCallback.handle(connection);
                }

            } else {
                // FIXME: you need third part lib to support upload files by using HttpClient
                // FIXME: so i didn't give an implementation, but you can simply find it on Google
                HttpResponse response = HttpClientUtil.execute(request);
                if (request.enableProgressUpdated) {
                    return request.iCallback.handle(HttpClientUtil.execute(request), new OnProgressUpdatedListener() {
                        @Override
                        public void onProgressUpdate(int curPos, int contentLength) {
                            publishProgress(Request.STATE_DOWNLOAD, curPos, contentLength);
                        }
                    });
                } else {
                    return request.iCallback.handle(HttpClientUtil.execute(request));
                }

            }
        } catch (HttpException e) {
            if (e.errorType == HttpException.ErrorType.TIMEOUT) {
                if (retry < request.maxRetryCount) {
                    retry++;
                    return request(retry);

                }
            }
            return e;
        }
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        // TODO 这里回调结果
        if (o instanceof HttpException) {
            if (request.onGlobalExceptionListener != null) {
                if (!request.onGlobalExceptionListener.handleException((HttpException) o)) {
                    request.iCallback.onFailure((HttpException) o);
                }
            } else {
                request.iCallback.onFailure((HttpException) o);
            }
        } else {
            request.iCallback.onSuccess(o);
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        // TODO 这里回调进度更新
        request.iCallback.onProgressUpdate(values[0], values[1], values[2]);
    }
}
